package com.hl.service.impl;

import com.alibaba.excel.EasyExcel;
import com.hl.listener.CustomerListener;
import com.hl.entity.Customer;
import com.hl.mapper.CustomerMapper;
import com.hl.response.Response;
import com.hl.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    CustomerMapper customerMapper;
    
    @Override
    @Transactional
    public Response importCustomers(MultipartFile file) throws IOException {
        Response result = new Response(200);
        FileMagic fileMagic = FileMagic.valueOf(new BufferedInputStream(file.getInputStream()));
        if (!Objects.equals(fileMagic, FileMagic.OLE2) && !Objects.equals(fileMagic, FileMagic.OOXML)) {
            result.setCode(500);
            result.setMsg("请上传 EXCEL 文件");
            return result;
        }
        int count = countBigCustomer();
        if (count != deleteAllBigCustomer()) {
            result.setCode(500);
            result.setMsg("清除数据失败！");
            return result;
        }
        EasyExcel.read(file.getInputStream(), Customer.class, new CustomerListener(customerMapper)).sheet().doRead();
        return result;
    }
    
    @Override
    public void addListCustomer(List<Customer> list) {
        customerMapper.insertList(list);
    }
    
    @Override
    public Customer queryByMemberId(String memberId) {
        return customerMapper.queryByMemberId(memberId);
    }
    
    @Override
    public int countBigCustomer() {
        return customerMapper.countCustomer();
    }
    
    @Override
    public int deleteAllBigCustomer() {
        return customerMapper.deleteAllCustomer();
    }
}